<template>
  <div class="mt-s-address">
    <ul class="mt-s-provinces">
      <li :class="{active: currentProvince.id === province.id}"
        v-for="(province, index) in provinces"
        :key="index"
        @click="selectProvince(index)">{{province.name}}</li>
    </ul>
    <ul class="mt-s-citys">
      <li :class="{active: c.id === city.id}"
       v-for="(c, index) in citys"
       :key="index"
       @click="cityChange(c)"
       >{{c.name}}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      provinces: [],
      citys: [],
      currentProvince: {
        id: 0,
        name: "全国",
        level: 1,
        upid: 0
      }
    }
  },
  props: {
    city: {
      type: Object,
      default: {
        id: 0,
        name: "全国",
        level: 1,
        upid: 0
      }
    },
    whole: {
      type: Number,
      default: 1 //0: 不包含全国; 1: 包含全国
    }
  },
  mounted() {
    this.getProvinces().then(() => {
      this.getCitys(this.city.upid)
    })
  },
  methods: {
    selectProvince(index) {
      this.currentProvince = this.provinces[index]
      this.getCitys(this.provinces[index].id)
    },
    async getCitys(pid) {
      this.$emit("showLoading")
      let citys
      if (this.whole)
        citys = await this.$store.dispatch("getCityWithWhole", pid)
      else citys = await this.$store.dispatch("getCity", pid)
      this.citys = citys
      this.$emit("stopLoading")
      return
    },
    cityChange(c) {
      this.$emit("changeCity", c)
    },
    getProvinces() {
      this.$emit("showLoading")
      return this.$store
        .dispatch("getProvincesWithWhole")
        .then(provinces => {
          this.$emit("stopLoading")
          this.provinces = provinces
        })
        .catch(e => {
          this.$emit("stopLoading")
          throw new Error(e)
        })
    }
  }
}
</script>

<style lang="scss">
.mt-s-address {
  & > .mt-s-provinces {
    flex: 4;
  }

  & > .mt-s-citys {
    flex: 6;
    background-color: #f0f0f0;
  }
}
</style>
